package org.npu.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CommentFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //1.调用请求对象读取请求包中请求行中的URI，了解用户访问的资源文件是谁
        String uri = req.getRequestURI();//[/网站名/资源文件名  /bigWeb/login.html   or  /myWeb/login]

        //2.如果用户要发表评论，则要确认用户已经登录，否则拒绝请求
        if (uri.contains("commentreceive") && req.getMethod().equals("POST")){
            Boolean usr = false;//默认用户没登录
            Boolean psd = false;//默认用户没登录
            Cookie[] cookieArray = null;
            resp.setContentType("text/html;charset=utf-8");
            cookieArray = req.getCookies();//读取Cookie
            for(Cookie c : cookieArray){
                if (c.getName().equals("username")) usr=true;
                else if (c.getName().equals("password")) psd=true;
            }
            if (usr && psd){
                //用户已经登录，放行
                System.out.println("用户已登录");
                filterChain.doFilter(req,resp);
                return;
            }else {
                //用户没登陆
                System.out.println("用户未登录");
                PrintWriter out = resp.getWriter();
                out.println("<center><h1>请点击右上角登录!</h1></center>");
                out.flush();
                out.close();
                return;
            }
        }

        //默认放行
        filterChain.doFilter(req,resp);
        return;

    }

    @Override
    public void destroy() {

    }
}
